<!-- 需求编辑页面 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #footer>
      <a-space
        ><a-button
          type="primary"
          @click="addDemand"
          v-if="demand.info.state === 1"
        >
          保存
        </a-button>
        <a-button
          type="primary"
          @click="addDemand"
          v-if="demand.info.state === 5"
        >
          修改
        </a-button>
        <a-button
          v-if="demand.info.state === 5"
          class="buttonNode"
          type="primary"
          @click="toClientOrder"
          >转入订单</a-button
        >
        <!-- <a-button
          v-if="demand.info.state === 6"
          type="outline"
          @click="goPreview"
        >
          <template #icon><icon-printer /></template>
          <template #default>预览PDF</template>
        </a-button>
        <a-button type="primary" v-print="printObj">
          <template #icon><icon-printer /></template>
          <template #default>打印订单</template>
        </a-button> -->
      </a-space>
    </template>
    <div>
      <div class="title-item">
        <a-space style="margin-left: 40px">
          <div
            style="
              width: 5px;
              height: 23px;
              background-color: rgba(61, 126, 255, 1);
              border: none;
              border-radius: 2px;
            "
          ></div>
          <div>基本信息</div></a-space
        >
      </div>
      <div class="form-item">
        <div class="demand-index">
          <a-form
            auto-label-width
            ref="form"
            :model="demand.info"
            :layout="(layout as Tlayout)"
          >
            <a-row :gutter="16">
              <a-col
                v-for="element in demandForm?.info?.design?.form"
                :key="element.id"
                :span="element.span"
              >
                <FormItem
                  :name="element.name"
                  :componentType="element.componentType"
                  v-model:props="element.props"
                  :required="element.required"
                  v-model:values="element.values"
                  :disabled="element.disabled"
                />
              </a-col>
            </a-row>
          </a-form>

          <ReviewApprovalDetail
            class="approve-item"
            :isProcess="isProcess"
            :approved="approved"
            :flowAuditData="flowAuditData"
            @finalAudit="finalAudit"
          />
          <PreviewModel
            ref="PreviewModelRef"
            v-model:visible="modelVisible"
            :orderInfo="demand.info"
          ></PreviewModel>
        </div>
      </div>

      <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
        <template #title> 提交需求 </template>
        <div
          style="display: flex; justify-content: center; align-items: center"
        >
          <a-space :size="40"
            ><a-form
              auto-label-width
              :model="demand.info"
              ref="formRef"
              :rules="rules"
            >
              <a-form-item
                field="processId"
                label="请选择审核组:"
                required
                label-col-flex="100px"
              >
                <a-select
                  style="width: 230px"
                  v-model="demand.info.processId"
                  placeholder="请选择"
                >
                  <a-option
                    v-for="item in flowProcess"
                    :key="item.id"
                    :value="item.id"
                    >{{ item.name }}</a-option
                  >
                </a-select>
              </a-form-item>
            </a-form>
          </a-space>
        </div>
      </a-modal>
    </div>
  </pageHeader>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import {
    getDemandFormStatusOn,
    postDemandForm,
    getOrderDemand,
    putDemandForm,
  } from '@/api/order-management/client-management/demand/demand';
  import * as apilist from '@/api/order-management/client-order/index';
  import { GetPersonnelinformation } from '@/api/home/System settings/personal-information/index';
  import { useRouter } from 'vue-router';
  import { getFlowProcessAll } from '@/api/order-management/client-order/index';
  import PreviewModel from './PreviewModel.vue';

  // const printObj = {
  //   id: 'printMe',
  // };
  const formRef = ref();
  const rules = reactive({
    processId: [{ required: true, message: '请选择审核组' }],
  });
  // 获取审核组数据
  const flowProcess = ref([]);
  const getFlowProcessData = async () => {
    const res = await getFlowProcessAll({ page: 1, size: 99999 });
    flowProcess.value = res.content;
  };
  getFlowProcessData();
  const userInfo = JSON.parse(sessionStorage.getItem('loginInfo') as any);
  const router = useRouter();
  const breadCrumb: string[] = ['需求管理', '客户需求', '需求详情'];
  const title: string = '需求详情';
  const layout = ref('vertical');
  const visible = ref(false);
  // type Tlayout = 'inline' | 'horizontal' | 'vertical' | undefined;
  const isProcess = ref(false);
  const flowAuditData = ref<any>({});
  const approved: any = ref([]);
  const modelVisible = ref(false);
  const demand = reactive<any>({
    info: {
      flow: null, //
      number: '', //编号
      clientCompanyId: null, //客户
      userStaffId: null, //业务经理
      contractId: '', //关联合同id
      customerId: '', //客户联系人id
      extend: '', //扩展
      orderTime: null, //订单时间
      invoiceInformation: '', //收款方式
      payMode: null, //付款方式
      remark: null, //备注
      invoiceId: null,
      orderTemplateId: null, //模板ID
      product: [], //产品详情
      delivery: [], //产品详情
      file: [],
      state: 0,
      collectionAccountId: null,
      processId: null,
    },
  });

  const GetStaffData = ref([]);
  const GetPersonnelData = async () => {
    const res = await GetPersonnelinformation({ page: 1, size: -1 });
    GetStaffData.value = res.content.data;
  };
  GetPersonnelData();

  interface DemandFormType {
    info: {
      design: {
        form: any[];
      };
    };
  }
  const demandForm = reactive<DemandFormType>({
    info: { design: { form: [] } },
  });

  const keys = Object.keys(demand.info);
  // 添加
  const addDemand = async () => {
    if (demand.info.state === 5) {
      visible.value = true;
    } else {
      demandForm.info.design.form.forEach((item) => {
        if (item.code === 'TABLE') {
          demand.info.product = item.props.data;
        }
        if (item.code === 'DELIVERY_REQUIREMENTS_BC') {
          demand.info.delivery = item.props.data;
        }

        if (item.code === 'FILE') {
          demand.info.file = item.props.data;
        }
        if (item.fieldName && keys.includes(item.fieldName)) {
          demand.info[item.fieldName] = item.values[0];
        }
      });
      demand.info.extend = JSON.stringify(demandForm.info.design.form);
      demand.info.state = 1;
      demand.info.customerId = Number(demand.info.customerId);
      demand.info.orderTime = new Date(demand.info.orderTime).toJSON();
      if (demand.info.delivery) {
        demand.info.delivery?.forEach((item: any) => {
          item.items.map((element: any) => {
            element.deliveryTime = new Date(element.deliveryTime).toJSON();
            return element;
          });
        });
      }

      //用户id需Number转数字
      delete demand.info.extends;
      let res = await putDemandForm(demand.info);
      router.back();
    }
  };

  const getFlowRel = (res: any) => {
    if (!res.length) return;
    const {
      createName,
      createPosition,
      reviewedName,
      reviewedPosition,
      createBy,
      reviewedBy,
      state,
    }: any = res[0];
    approved.value.push({
      flowNodeType: 1,
      createName,
      createPosition,
      show: true,
      state: 1,
      createBy,
    });

    res.forEach((item) => {
      approved.value.push({
        flowNodeType: 2,
        reviewedName: item.reviewedName,
        reviewedPosition: item.reviewedPosition,
        show: true,
        reviewedBy: item.reviewedBy,
        state: item.state,
        remark: item.remark,
      });
    });
  };

  const getDemandInfo = async (id: number) => {
    let res = await getOrderDemand({ id });
    demand.info = res;
    getFlowRel(res.flowRel);
    demandForm.info.design.form = JSON.parse(res.extend);
    demandForm.info.design.form.sort((a: any, b: any) => a.sort - b.sort);
    demandForm.info.design.form.forEach((item: any) => {
      if (res.state !== 1 && res.state !== 5) item.disabled = true;
      if (item.code === 'NUMBER-UNIVERSAL') {
        item.values = [demand.info.number];
      }
      if (item.componentType === 'FILE') {
        item.props.data = res.file;
      }
      if (item.componentType === 'ORDER_TIME') {
        item.values = [demand.info.createdAt];
      }
      if (item.componentType === 'TABLE') {
        item.props.data = demand.info.product;
      }
    });
  };
  const formTemplate = ref([]);

  const finalAudit = (data: any) => {};

  const goPreview = () => {
    modelVisible.value = true;
  };

  const handleOk = async () => {
    console.log(demandForm.info, demand.info); // 控件对应上字段
    demandForm.info.design.form?.forEach((item) => {
      if (item.code === 'TABLE') {
        demand.info.product = item.props.data;
      }
      if (item.code === 'FILE') {
        demand.info.file = item.props.data;
      }
      if (item.code === 'DELIVERY_REQUIREMENTS_BC') {
        demand.info.delivery = item.props.data;
      }
      if (item.fieldName && keys.includes(item.fieldName)) {
        demand.info[item.fieldName] = item.values[0];
      }
    });

    demand.info.extend = JSON.stringify(demandForm.info.design.form);
    demand.info.customerId = Number(demand.info.customerId);
    demand.info.orderTime = new Date(demand.info.orderTime).toJSON();
    demand.info.delivery?.forEach((item: any) => {
      item.items.map((element: any) => {
        element.deliveryTime = new Date(element.deliveryTime).toJSON();
        return element;
      });
    });
    delete demand.info.extends;
    demand.info.orderProduct?.forEach((item) => {
      item.demandId = demand.info.id;
      delete item.id;
    });
    await putDemandForm(demand.info);
    router.back();
  };

  const toClientOrder = async () => {
    demandForm.info.design.form.forEach((item) => {
      if (item.code === 'TABLE') {
        demand.info.orderProduct = item.props.data;
        demand.info.totalPrice = item.props.totalPrice;
      }
      if (item.code === 'FILE') {
        demand.info.file = item.props.data;
      }
      if (item.code === 'DELIVERY_REQUIREMENTS_BC') {
        demand.info.delivery = item.props.data;
        demand.info.delivery.forEach((item: any) => {
          item.items.map((element: any) => {
            element.deliveryTime = new Date(element.deliveryTime).toJSON();
            return element;
          });
        });
      }
    });
    demand.info.extend = JSON.stringify(demandForm.info.design.form);
    delete demand.info.extends;
    demand.info.state = 1;
    demand.info.customerId = Number(demand.info.customerId);
    demand.info.orderTime = new Date(demand.info.orderTime).toJSON();
    demand.info.orderProduct.forEach((item) => {
      item.demandId = demand.info.id;
      delete item.id;
    });
    await apilist.toClientOrder(demand.info);
    router.push({
      name: 'SalesOrder',
    });
  };

  onMounted(() => {
    // 如果是添加则获取状态开启的那个模板
    // getByTemplateStatusOn()
    // 如果是编辑则获取对应的模板
    let demandId = Number(router.currentRoute.value.query.id);
    demand.info.id = demandId;
    getDemandInfo(demandId);
  });
</script>

<style scoped lang="less">
  .title-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
    margin-top: 20px;
  }
  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }

  .demand-index {
    padding: 15px 40px;
    width: 95%;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
  }

  .success {
    position: absolute;
    right: 30px;
    background-color: #31c27c;
    color: #fff;
    border-radius: 100%;
    width: 50px;
    text-align: center;
  }

  .blacklist {
    position: absolute;
    right: 30px;
    background-color: red;
    color: #fff;
    margin-left: 20px;
    border-radius: 100%;
    width: 50px;
    text-align: center;
  }

  .title-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
    margin-top: 20px;
  }

  .unchecked-radio {
    background-color: #fff;
    color: #dcdfe6;
    border: 1px solid #dcdfe6;
    font-weight: 700;
    font-size: 16px;
  }
  .checked-radio {
    background-color: rgb(49, 194, 124);
    color: #fff;
    border: 1px solid rgb(49, 194, 124);
    font-weight: 700;
    font-size: 16px;
  }

  .checked-radio-no {
    background-color: rgb(255, 0, 0);
    color: #fff;
    border: 1px solid rgb(255, 0, 0);
    font-weight: 700;
    font-size: 16px;
  }
  .radio-icon-box-checked {
    border: 1px solid rgb(49, 194, 124);
    background-color: #fff;
  }
  .radio-icon-box-checked-no {
    border: 1px solid rgb(255, 0, 0);
    background-color: #fff;
  }
  .radio-icon-box-unchecked {
    border: 1px solid rgba(220, 223, 230, 1);
  }
  .radio-icon-checked {
    color: rgb(49, 194, 124);
  }

  .radio-icon-checked-no {
    color: rgb(255, 0, 0);
  }

  .radio-icon-unchecked {
  }
  .radio-icon {
    position: relative;
    top: 3px;
  }

  .approve-item {
    margin: 25px auto;
    width: 30%;
    background-color: rgba(255, 255, 255, 1);
    border-radius: 8px;
    // -moz-box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.349019607843137);
    // -webkit-box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.349019607843137);
    box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.349019607843137);
    height: 600px;
  }

  .form-item {
    width: 100%;
  }

  ::v-deep .arco-form {
    width: 65%;
  }

  @media print {
    /* 隐藏页眉和页脚 */
    @page {
      margin: 0;
    }
    @top-center {
      content: none;
    }
    @bottom-center {
      content: none;
    }
  }

  .items {
    padding-top: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .buttonNode {
    text-align: right;
  }
  .Node-title {
    justify-content: space-between;
    width: 100%;
    background: inherit;
    background-color: rgba(255, 255, 255, 1);
    border: none;
    border-radius: 4px;
    // -moz-box-shadow: 1px 1px 5px rgba(153, 153, 153, 0.349019607843137);
    // -webkit-box-shadow: 1px 1px 5px rgba(153, 153, 153, 0.349019607843137);
    // box-shadow: 1px 1px 5px rgba(153, 153, 153, 0.34);
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
  }
</style>
